<template>
  <div class="dept-tree-select">
    <el-popover
      placement="bottom-start"
      class="orgTree"
      trigger="click"
      v-model="treeShow"
    >
      <div class="tree-wrap">
        <el-tree
          :data="companyTableData"
          :props="defaultProps"
          :expand-on-click-node="false"
          node-key="id"
          style="width: 300px"
          @node-click="handleNodeClick"
        ></el-tree>
      </div>
      <el-input
        slot="reference"
        ref="input"
        v-model="form.deptName"
        clearable
        :readonly="true"
        style="width: 100%"
        placeholder="请选择部门"
      >
      </el-input>
    </el-popover>
    <i
      @click.stop="closeName1"
      class="el-icon-circle-close"
      v-if="form.deptName"
    ></i>
    <i class="el-icon-arrow-down" v-else></i>
  </div>
</template>
<script>
import { tbDeptQuery } from '@/api/admin/user/tbSysDept.js'
export default {
  data() {
    return {
      treeShow: false,
      companyTableData: [],
      defaultProps: {
        children: 'childList',
        label: 'name',
      },
      form: {
        deptName: '',
        deptCode: '',
      },
    }
  },
  watch: {
    defaultValue(v) {
      this.form.deptName = v || ''
    },
    $route() {
      this.form.deptName = ''
    },
  },
  props: ['defaultValue'],
  mounted() {
    this.form.deptName = this.defaultValue || ''
    this.getList()
  },
  methods: {
    //查询部门
    getList() {
      tbDeptQuery({ pId: '0' }).then((res) => {
        let { data } = res.data
        let { userId, userType, deptFullData } = this.$store.getters
        if (userType == 1) {
          //超管
          this.companyTableData = data
        } else {
          //普通管理员
          if (!data.length || data.hasOwnProperty('childList')) return
          let fullDept = data[0].childList
          if (
            deptFullData.hasOwnProperty('childList') &&
            deptFullData.childList.length
          ) {
            let schoolDept = deptFullData.childList[0].id
            this.companyTableData = fullDept.filter((v) => v.id == schoolDept)
          }
        }
      })
    },
    // 选中上一级单位
    handleNodeClick(val) {
      this.form.deptName = val.name
      this.form.deptCode = val.code
      this.$emit('e-emit', val)
      this.treeShow = false
    },
    // 清空上一级部门
    closeName1() {
      this.form.deptName = ''
      this.treeShow = false
      this.$emit('e-emit', '')
    },
  },
}
</script>
<style scoped lang="scss">
.tree-wrap {
  max-height: 300px;
  overflow-y: scroll;
}
.tree-wrap::-webkit-scrollbar {
  display: none;
}
.dept-tree-select {
  position: relative;
  i.el-icon-circle-close,
  i.el-icon-arrow-down {
    position: absolute;
    right: 18px;
    top: 13px;
    cursor: pointer;
    color: #c2cadb;
  }
}
</style>